import { observable, action, runInAction } from "mobx";
import * as api from "../../service/api/standard_face_database_api";
import { base64_to_str, str_to_base64, deep_copy } from "../../utils/utils";
import { FACELOGIN } from '../../service/api/AdminApi'
import { Menu, Button, Input, message, Modal, Checkbox, Pagination } from "antd";
import AdminStore from './AdminStore'
import { toJS } from 'mobx'
import $ from 'jquery'
class standard_face_database_store {
  @observable newFaceStoreList = []//新建的人脸库
  @observable faceStoreList = []//人脸库详细信息
  @observable nowChoseWhichFaceStore = undefined
  @observable checkedList = []
  @observable load_face_img = false//什么时候加载图片，在数据渲染好之后

  @observable DeleteHumanBodySuccessArray = []
  @action HumanCharacterLibraryRemovesElements = async (ID, nowChoseWhichFaceStore, token) => {
    let DeleteHumanBodySuccessArray = [];
    await api.HumanCharacterLibraryRemovesElements(ID, nowChoseWhichFaceStore, token).then(res => {
      console.log(res);
      if (res.code === 200) {
        DeleteHumanBodySuccessArray.push(ID);
        console.log(`人脸库删除人脸${ID}success`);
      }
    });
  };
  @action DeleteImageFun = async (src) => {
    let DeletePictureSuccessArray = []
    const DeleteTheImageFunctionResult = await api.DeleteImageVideoLibraryInsertFunction(src)
    if (DeleteTheImageFunctionResult.code === 200) {
      console.log(`删除图片${src}success`);
      DeletePictureSuccessArray.push(src);
    } else if (DeleteTheImageFunctionResult.code === 400) {
      console.log(`删除图片${src}fail,没有找到该图片`);
    } else {
      console.log(`删除图片${src}fail`);
    }
  };
  @action change_load_face_img = (condition) => {
    this.load_face_img = condition
  }
  @action change_checkedList = (checkedList) => {
    this.checkedList = checkedList
  }
  @action human_feature_library_search_elements = async (vector, userName, token) => {
    let human_feature_library_search_element_results = {}
    let vecList = "base64://" + encodeURIComponent(vector);
    const formData = new FormData();
    formData.append("src", vecList);
    formData.append("top", 200);
    const res = await api.face_search_element(formData, userName, token)
    console.log(res);
    if (res.data.length > 0) {
      //data中有数据直接取data的数据
      //处理data中返回的数据
      res.data.forEach(function (item) {
        item.score = String(item.score).substring(0, 5);
      });
      human_feature_library_search_element_results.information_array = res.data
    } else {
      let score_bigger_than_80 = [];
      for (let [index, each_item] of res.debug.entries()) {
        if (each_item.score >= 80) {
          score_bigger_than_80.push(each_item);
        }
      }
      //冒泡排序
      for (let i = 0; i < score_bigger_than_80.length - 1; i++) {
        for (let j = 0; j < score_bigger_than_80.length - 1 - i; j++) {
          if (
            score_bigger_than_80[j].score >
            score_bigger_than_80[j + 1].score
          ) {
            var temp = score_bigger_than_80[j].score;
            score_bigger_than_80[j].score =
              score_bigger_than_80[j + 1].score;
            score_bigger_than_80[j + 1].score = temp;
          }
        }
      }
      human_feature_library_search_element_results.information_array = score_bigger_than_80;
    }

    //这里已经获取到需要的数组，对数据进行五次方处理，返回大于70分的人

    console.log(human_feature_library_search_element_results)

    let new_human_feature_library_search_element_results = deep_copy(human_feature_library_search_element_results)

    for (let [index, item] of new_human_feature_library_search_element_results.information_array.entries()) {
      // item.score = (Math.pow(item.score / 100, 5) * 100).toFixed(2)
      console.log(item)
      item.score = Number(item.score).toFixed(2)
    }


    let i = new_human_feature_library_search_element_results.information_array.length
    while (i--) {
      if (new_human_feature_library_search_element_results.information_array[i].score < 80) {
        new_human_feature_library_search_element_results.information_array.splice(i, 1)
      }
    }

    if (new_human_feature_library_search_element_results.information_array.length > 0) {
      new_human_feature_library_search_element_results.result = 'people_found'
    } else {
      new_human_feature_library_search_element_results.result = 'no_people_found'
    }

    return new_human_feature_library_search_element_results
  };
  //列出特征库所有元素
  @action ListsAllElementsOfTheFeatureLibrary = async (userName, token) => {
    let AllElementsOfTheFeatureLibrary = [];
    await api.ListsAllElementsOfTheFeatureLibrary(userName, token).then(res => {
      console.log(res);
      if (res.code === 200) {
        runInAction(() => {
          AllElementsOfTheFeatureLibrary = res.data.result;
        });
      }
    });
    return AllElementsOfTheFeatureLibrary;
  };
  @action HumanFeatureExtractionFun = async file => {
    let HumanFeatureExtractionCondition = {};
    const formData = new FormData();
    formData.append("src", file);
    formData.append("croped", "0");
    const res = await FACELOGIN(formData);
    console.log(res);

    if (res.code === 200) {
      if (res.data.length > 0) {
        HumanFeatureExtractionCondition.condition = "success";
        let CurrentMaximumData = undefined//当前最大的数据
        for (let [index, item] of res.data.entries()) {
          if (index === 0) {
            CurrentMaximumData = item
          } else {
            CurrentMaximumData.w > item.w ? CurrentMaximumData : CurrentMaximumData = item
          }
        }
        HumanFeatureExtractionCondition.feature_vector = CurrentMaximumData.vec;
        HumanFeatureExtractionCondition.body_position = CurrentMaximumData
      } else {
        HumanFeatureExtractionCondition.condition = "fail";
      }
    }

    return HumanFeatureExtractionCondition;
  };
  @action upload_img = async (img_base64, people_name, nowChoseWhichFaceStore, token) => {
    let result = false
    let imgUrl = img_base64;
    imgUrl = imgUrl.replace("data:image/png;base64,", "");
    imgUrl = imgUrl.replace("data:image/jpg;base64,", "");
    imgUrl = imgUrl.replace("data:image/jpeg;base64,", "");
    let params = new FormData();
    params.append("src", "base64://" + encodeURIComponent(imgUrl)); //抓取特征所用的FormData
    const res = await FACELOGIN(params)
    console.log(res)
    if (res.code === 200) {
      try {
        if (res.data[0].vec) {
          //存在人脸
          let vecList = "base64://" + encodeURIComponent(res.data[0].vec);
          let params = new FormData();
          params.append("src", vecList);
          params.append("ID", nowChoseWhichFaceStore);
          params.append("uid", str_to_base64(people_name));
          params.append("nick", str_to_base64(people_name));
          const res1 = await api.insert_to_databse(nowChoseWhichFaceStore, token, params)
          console.log(res1)
          if (res1.code === 200) {
            let params = new FormData();
            params.append("src", "base64://" + encodeURIComponent(imgUrl));
            params.append("fid", str_to_base64(base64_to_str(nowChoseWhichFaceStore) + people_name));
            const res2 = await api.storage_img(token, params)
            console.log(res2)
            if (res2.code == 200) {
              result = true
              console.log(str_to_base64(base64_to_str(nowChoseWhichFaceStore) + people_name) + `图片存储成功`)
            } else if (res2.code === 400) {
              message.error('人脸名称已存在,请尝试换一个名称')
            }
          } else if (res1.code === 422) {
            message.info("人脸名称已存在,请尝试换一个名称");
          }
        }
      } catch (err) {
        message.info("您上传的图片中没有包含人脸");
      }
    }
    return result
  }

  @action choose_this_database = (item) => {
    this.nowChoseWhichFaceStore = item
  }
  @action del_faceStore_name = async (nowChoseWhichFaceStore, token) => {
    let result = false
    if (nowChoseWhichFaceStore) {
      Modal.confirm({
        centered: true,
        title: "请确认是否删除人脸库",
        className: "modal_comfirm",
        width: "300px",
        content: "",
        okText: "确认",
        okType: "danger",
        cancelText: "取消",
        onOk: async () => {
          const res = await api.del_faceStore_name(nowChoseWhichFaceStore, token);
          console.log(res)
          if (res.code === 200) {
            const res = await this.get_face_database(AdminStore.token)
            console.log(toJS(res))
            if (res.length > 0) {
              $((function () {
                $('#menu0').click()
              }))
            } else {
              runInAction(() => {
                this.faceStoreList = []
              })

            }

          }
        },
        onCancel() { }
      });
    }

  }
  @action get_face_database = async (token) => {
    const res = await api.get_face_database(token)
    console.log(res)
    runInAction(() => {
      if (res.code === 200) {
        this.newFaceStoreList = res.data.result
      }
    })
    return this.newFaceStoreList
  };


  @action get_database_information = async (per_page, page, which_database, token) => {
    console.log(which_database)
    const res = await api.get_database_information(per_page, page, which_database, token)
    console.log(res)
  };

  @action save_face_store = async (inputValue, token) => {
    let params = new FormData();
    let result = undefined
    params.append("libid", str_to_base64(inputValue));
    const res = await api.save_face_store(params, token)
    console.log(res)
    if (res.code === 200) {
      await this.get_face_database(token)
      result = 'success'
    } else if (res.code === 500) {
      message.info('人脸库名称已存在，请尝试换一个人脸库名称')
    }
    else {
      result = 'failed'
    }
    return result
  }
  @action get_face_store_information = async (item, per_page, token) => {
    this.faceStoreList = []
    const res = await api.get_face_store_information(item, per_page, token)
    console.log(res)
    runInAction(() => {
      if (res.code === 200) {
        this.faceStoreList = res.data.result
        return ('success')
      }
    })
    return 'failed'
  }





}

export default new standard_face_database_store();
